package com.water.app.Config;

import cn.hutool.json.JSONUtil;
import com.water.app.JwtUtil;
import com.water.app.PrivateChatMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.converter.MappingJackson2MessageConverter;
import org.springframework.messaging.converter.MessageConverter;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

import java.nio.charset.StandardCharsets;
import java.security.Principal;
import java.util.List;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer{


    private static final Logger log = LoggerFactory.getLogger(WebSocketConfig.class);

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/stomp")
                .setAllowedOriginPatterns("*")
                .withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.setApplicationDestinationPrefixes("/app")
                .setUserDestinationPrefix("/user")
                .enableSimpleBroker("topic","queue");
    }


    @Override
    public boolean configureMessageConverters(List<MessageConverter> messageConverters) {
        return messageConverters.add(new MappingJackson2MessageConverter());
    }

    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(new ChannelInterceptor() {
            @Override
            public Message<?> preSend(Message<?> message, MessageChannel channel) {
                StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
                //处理connect命令
                if(accessor!=null&&StompCommand.CONNECT.equals(accessor.getCommand())){
                    try {
                        String token = accessor.getFirstNativeHeader("auth-token");
                        int userId = JwtUtil.parseJwt(token);
                        if(userId==-1){
                            log.info("令牌过期，断开连接");
                            return null;
                        }
                        accessor.setUser(()->String.valueOf(userId));
                        System.out.printf("🔗 JWT 校验通过，绑定用户：%d 到连接%n", userId);
                    } catch (Exception e) {
                        System.out.println("连接校验未知异常，拒绝连接");
                        return null;
                    }
                }
                else if(accessor!=null&&StompCommand.SEND.equals(accessor.getCommand())){
                    Principal user = accessor.getUser();
                    if(user==null){
                        log.info("用户未登录，拒绝连接");
                        return null;
                    }
                    String userId = user.getName();
                    Object payload = message.getPayload();
                    if(payload instanceof byte[] payloadByte){
                        String jsonStr=new String(payloadByte, StandardCharsets.UTF_8);
                        PrivateChatMsg bean = JSONUtil.toBean(jsonStr, PrivateChatMsg.class);
                        String sender = String.valueOf(bean.getSender());
                        if (!userId.equals(sender)){
                            return null;
                        }
                    }
                }
                return message;
            }
        });
    }
}
